package com.hnust.controller;

import com.hnust.domain.record.NewQuestionRecord;
import com.hnust.service.UpLoadService;
import com.hnust.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/upload")
public class UploadController {

	@Autowired
	UpLoadService upLoadService;

	/*
	 * @Author Tonited
	 * @Description //TODO 读取题目文件并返回题目列表
	 * @Date 17:26 2020/10/30
	 * @Param [file, courseId]
	 * @return com.hnust.util.Result<java.util.List<com.hnust.domain.record.NewQuestionRecord>>
	 **/
	@PostMapping("questions")
	public Result<List<NewQuestionRecord>> uploadQuestions(@RequestPart("file") MultipartFile file,
														   @RequestPart("courseId") String courseId) {
		String msg = "成功";
		int code = 1;
		List<NewQuestionRecord> list = null;
		try{
			Map<String, Object> res = upLoadService.readQuestions(file, courseId);
			list = (List<NewQuestionRecord>) res.get("list");
			msg = (String) res.get("msg");
		} catch (Exception e) {
			msg = e.getMessage();
			code = 0;
		}
		return new Result<List<NewQuestionRecord>>(code,msg,list);
	}

	/**
	 * 兼容新版本的文件上传接口
	 */
	@PostMapping("v2/questions")
	public Result<List<NewQuestionRecord>> uploadQuestionsV2(@RequestPart("file") MultipartFile file,
														   @RequestParam("courseId") String courseId) {
		String msg = "成功";
		int code = 1;
		List<NewQuestionRecord> list = null;
		try{
			Map<String, Object> res = upLoadService.readQuestions(file, courseId);
			list = (List<NewQuestionRecord>) res.get("list");
			msg = (String) res.get("msg");
		} catch (Exception e) {
			msg = e.getMessage();
			code = 0;
		}
		return new Result<List<NewQuestionRecord>>(code,msg,list);
	}
}
